<?php

declare(strict_types=1);

namespace app\yperp\command;

use DateTime;
use app\yperp\common\SuosiHttp;
use think\console\Command;
use think\console\Input;

use think\console\Output;

use GuzzleHttp\Client;

use GuzzleHttp\Psr7\Request;

use think\Db;

class suosibase extends Command
{
    use SuosiHttp;
    protected $output;

    protected $input;
    protected $driver;
    protected $windows = [];
    protected $cookies = [];
    protected $token = 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2luZm8iOiIlN0IlMjJhdmF0YXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRndld29yay5xcGljLmNuJTJGd3dwaWMzYXolMkY5OTU3ODZfTnc0YXFZZEZTamFHbmpVXzE3MTYyNzc3MzMlMkYwJTIyJTJDJTIyY29ycElkJTIyJTNBJTIyd3cyYjFhOGVkZGIzMjcyZmZiJTIyJTJDJTIyaW5kdXN0cnlUeXBlJTIyJTNBJTIybXl0eGwlMjIlMkMlMjJsb2dpblR5cGUlMjIlM0ElMjJub3JtYWwlMjIlMkMlMjJtZW1iZXJJZCUyMiUzQTE3NjA5Mjg5MjA1MjY1ODAxMTMlMkMlMjJtZW1iZXJOYW1lJTIyJTNBJTIyJUU2JTlEJThFJUU0JUI4JTk2JUU1JUI5JUIzJTIyJTJDJTIybW9iaWxlJTIyJTNBJTIyMTg5ODExNDAxMDElMjIlMkMlMjJvcmdJZCUyMiUzQTEwMDAxMCUyQyUyMm9yZ05hbWUlMjIlM0ElMjIlRTklOTUlQkYlRTglOTklQjklRUYlQkMlODglRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlRUYlQkMlODklMjIlMkMlMjJvcmdUeXBlJTIyJTNBJTIyZ2VuZXJhbCUyMiUyQyUyMnJlZ2lvbkNvZGUlMjIlM0ElMjIwMDAwMDAwMDAwMDAwMDAwMDAlMjIlMkMlMjJzaG9ydE5hbWUlMjIlM0ElMjIlRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlMjIlMkMlMjJ1c2VySWQlMjIlM0ExNzYwOTI4OTIwNTI2NTgwMTEzJTJDJTIydXNlck5hbWUlMjIlM0ElMjIlRTYlOUQlOEUlRTQlQjglOTYlRTUlQjklQjMlMjIlMkMlMjJ1c2VyVHlwZSUyMiUzQSUyMmVtcGxveWVlJTIyJTdEIiwidXNlcl9uYW1lIjoiMTAwMDEwOzE3NjA5Mjg5MjA1MjY1ODAxMTM7ZW1wbG95ZWU7bm9ybWFsIiwib3JnX2lkIjoxMDAwMTAsInNjb3BlIjpbImFsbCJdLCJleHAiOjE3Mjc4NTAwNTMsImp0aSI6ImMxMTdkZDMzLTVlZTgtNDc5Ny1hZmUyLTJjMDBiMDg5ZWIzNSIsImNsaWVudF9pZCI6InByb2R1Y3Rpb24ifQ.VxAGVizJAZIJ4l-bSauocWHgcTSbWxByuhnbESPalN_-jsO7EoMmsdSFXdMbNSfsCRfycfNrOenP_F4lPHzkQp44Bu9-jJUSR-VrHP2DkPJpLQCWQn2RXoj1CtVSzRpnt1c6KdvxccDmWbgfAVfDa39Y4QRse3hTpnYqaYTsusQ';
    public $presion_grpup_ids = [ //员工活码分组 https://m.suosishequ.com/rhyysshl/pc/child-manager/sop/sop-tool/employee/1/liveCode-group/group/
        '芜湖' => '1794921854150549506',
        '合肥' => '1793134835194183681',
        '成都' => '1781208814111330306',
        '绵阳' => '1780805443831369730',
        '重庆' => '1773036129085140994',
        '虹创' => '1763096116967170050',
        '测试' => '1760952172240629761'
    ];

    public $massage_tmpl_group_ids = [  //话术分组 https://m.suosishequ.com/rhyysshl/pc/child-manager/notice/speechcraft/article/0/cms-news/news/
        '芜湖' => '1794918166612094978',
        '合肥' => '1793135817821667329',
        '成都' => '1781208315725590529',
        '绵阳' => '1780811032366395393',
        '重庆' => '1772467865021087746',
        '虹创' => '1779833388841807874',
    ];
    public $grpup_grpup_ids = [
        '芜湖' => '1794922357957763073',
        '合肥' => '1793135207802933249',
        '成都' => '1784914950324916225',
        '绵阳' => '1784915354635022338',
        '重庆' => '1772508002709778434',
        '虹创' => '1763088628184178690',
    ];
    // 群活码分组id
    public $grpup_ids = [
        '1794922357957763073' => '芜湖',
        '1793135207802933249' => '合肥',
        '1784914950324916225' => '成都',
        '1784915354635022338' => '绵阳',
        '1772508002709778434' => '重庆',
        // '1763088628184178690' => '虹创',
    ];
    public $grpup_content_ids = [
        '空调中心' => '1787304428176216065',
        '冰洗中心' => '1787304368651841538',
        '电视中心' => '1787304312111435778',
    ];
    protected function configure()
    {
        // 指令配置
        $this->setName('suosi')
            ->setDescription('批量更新群标签');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->input = $input;

        $this->output = $output;

        try {

            // dump(mb_strlen('吴琼芳-15983771290-绵阳空调中心心', 'utf-8'));
            // $params['preson_qr_name']='吴琼芳-15983771290-绵阳空调中心-仪陇阳光精品店仪陇阳光精品店仪陇阳光精品店仪陇阳光精品店仪陇阳光精品店仪陇阳光精品店仪陇阳光精品店仪陇阳光精品店';
            // $params['preson_qr_name'] = (mb_strlen($params['preson_qr_name'], 'UTF-8') > 30) ? mb_substr($params['preson_qr_name'], 0, 30, 'UTF-8') : $params['preson_qr_name'];
            // dump(['update-$params' => $params]);
            // die;
            // $this->go();
            $this->update_base_user();
        } catch (\Throwable $th) {
            dump($th->getMessage());
            dump($th->getTraceAsString());
        }
    }
    /**
     * 更新活码的 “包含员工或部门”
     * @return void
     */
    function update_base_user()
    {
        $list = [
            '芜湖' => '1794921854150549506',
            '合肥' => '1793134835194183681',
            '成都' => '1781208814111330306',
            '绵阳' => '1780805443831369730',
            '重庆' => '1773036129085140994',
        ];

        // $userDeptList = $this->method_user_search_all('李世平', ['id' => ['1760928920526580113']]);
        // dump($userDeptList);die;

        foreach ($list as $id) {
            # code...

            $staffList = $this->get_staff_qr_list_by_yieid('', $id);
            foreach ($staffList as $staffes) {
                // dump($staffes);die;
                // continue;
                foreach ($staffes as $staff) {
                    # code...

                    $data = $this->getUserQRUpdateDetail($staff['id']);
                    $newData = $data['formValue'];
                    if (
                        in_array($newData['groupId'], $list)
                    ) {
                        unset($newData['deletedFlag']);
                        unset($newData['statFlag']);
                        unset($newData['statFlagName']);
                        unset($newData['configId']);
                        unset($newData['groupName']);
                        $userDeptList = $this->method_user_search_all('李世平', ['id' => ['1760928920526580113']]);
                        dump(['$userDeptList',$userDeptList]);
                        $newData['statFlagIdList'] = [];
                        $newData['userDeptList'] = $userDeptList;
                        dump('--------------------------------');
                        dump($newData);
                        dump('--------------------------------');
                    
                        $response = $this->update_preson_qr_by_param($newData);
                        dump(['update_base_user' => $response, '$newData' => $newData]);
                        unset($newData);
                    }

                }
            }
        }
    }
    function go()
    {
        $users = Db::table('dp_suosi_user')
            // ->where('id > 300')
            // ->where('username', '王平')
            ->whereIn('username', [
                "车国群",
                // '王倩1',

            ])
            // ->where('dep', '成都')
            // ->where('phone','13808179361')
            // ->where('dep_type', '芜湖冰洗')
            // ->limit(32, 2)
            ->select();
        //创建用户
        // try {
        //code...
        dump($users);
        // $users =    Db::query("SELECT * FROM `yp_erp_lhp`.`dp_suosi_user` WHERE `dep` LIKE '%绵阳%' AND `username` LIKE '%侯丽%' OR `username` LIKE '%梁双亚%' OR `username` LIKE '%陶雪梅%' OR `username` LIKE '%王月晴%' OR `username` LIKE '%高建梅%' OR `username` LIKE '%赵静%' OR `username` LIKE '%林佳%' OR `username` LIKE '%张莉%'");
        foreach ($users as $user) {
            //自动创建员工标签
            //自动创建部门标签
            //自动创建中心标签

            $this->craete_preson_qrs($user);
            $this->create_group_qrs($user);
            $this->upload_group_qr_to_msg_tmpl($user);
            $this->update_preson_qrs($user);
            $this->update_group_qrs($user);
        }

        // } catch (\Throwable $th) {
        //     //throw $th;
        // }
    }

    function update_group_qrs($user)
    {
        dump('----------------update_group_qrs start
         -------------------');

        $group_qr_list = $this->search_group_qr_one($user['dep_name']);
        dump($group_qr_list);
        foreach ($group_qr_list as $group_qr) {
            $param = [
                'id' => $group_qr['id'],
                'shopname' => $user['dep_name'],
                'name' => $user['username'],
                'dept_type' => $user['dep'] . $user['dep_type'] . '中心',
                'groupName' => $user['dep_name'],
                'dep' => $user['dep'],
                'BaseName' => '长虹美菱会员福利群-' . $user['dep_name'],
            ];

            $param['dep'] = $this->grpup_grpup_ids[$param['dep']];

            $this->update_group_qr($param);
            dump('----------------update_group_qrs end -------------------');

        }
    }
    function create_group_qrs($user)
    {
        $param = [
            'shopname' => $user['dep_name'],
            'name' => $user['username'],
            'dept_type' => $user['dep'] . $user['dep_type'] . '中心',
            'groupName' => $user['dep_name'],
            'dep' => $user['dep'],
            'BaseName' => '长虹美菱会员福利群-' . $user['dep_name'],
        ];

        $param['dep'] = $this->grpup_grpup_ids[$param['dep']];
        dump("创建群活码");
        $data = $this->create_group_qr($param);

        if ($data['success'] || $data['msg'] == '活码名称已存在') {
            $user = Db::table('dp_suosi_user1')->where(['id' => $user['id']])->update(['group_qr_status' => 1]);
            dump($user);
        } else {
            $user = Db::table('dp_suosi_user1')->where(['id' => $user['id']])->update(['group_qr_status' => 0, 'group_qr' => json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
            dump($user);
        }
    }
    function craete_preson_qrs($user)
    {

        $params = [
            'name' => $user['username'],
            'groupId' => $this->presion_grpup_ids[$user['dep']],
            'check_dept' => $user['dep'] . '分部' . $user['dep_type'] . '导购员',
            // 'check_dept' =>   '导购员',绵阳分部电视导购员
            'shopname' => $user['dep_name'],
            'dept_type' => $user['dep'] . $user['dep_type'] . '中心'
        ];


        dump(['create' => $params]);
        $data = $this->save_preson_qr($params);
        dump($data);
        if ($data['success']) {
            $user = Db::table('dp_suosi_user')->where($user)->update(['preson_qr_status' => 1]);
            dump($user);
        } else {
            $user = Db::table('dp_suosi_user')->where($user)->update(['preson_qr_status' => 0, 'preson_qr' => json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
            dump($user);
        }

    }
    function update_preson_qrs($user)
    {
        dump($user['dep']);
        $presion_grpup_id = $this->presion_grpup_ids[$user['dep']];
        dump($presion_grpup_id);
        // $presion_grpup_id =  '1793134835194183681';
        $users = $this->search_staff_qr_one($user['username'], $presion_grpup_id);
        dump($users);
        foreach ($users as $staff) {

            $params = [
                'id' => $staff['id'],
                'name' => $user['username'],
                'groupId' => $this->presion_grpup_ids[$user['dep']],
                'check_dept' => $user['dep'] . '分部' . $user['dep_type'] . '导购员',
                // 'check_dept' =>   '导购员',
                'shopname' => $user['dep_name'],
                'dept_type' => $user['dep'] . $user['dep_type'] . '中心',
                'preson_qr_name' => $user['username'] . '-' . $user['phone'] . '-' . $user['dep'] . $user['dep_type'] . '中心' . '-' . $user['dep_name']
            ];
            $params['preson_qr_name'] = (mb_strlen($params['preson_qr_name'], 'UTF-8') > 30) ? mb_substr($params['preson_qr_name'], 0, 30, 'UTF-8') : $params['preson_qr_name'];
            dump(['update-$params' => $params]);

            $data = $this->update_preson_qr($params);
            dump(['update-response' => $data]);
            if ($data['success']) {
                $user = Db::table('dp_suosi_user')->where($user)->update(['preson_qr_status' => 1]);
                dump($user);
            } else {
                $user = Db::table('dp_suosi_user')->where($user)->update(['preson_qr_status' => 0, 'preson_qr' => json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
                dump($user);
            }

        }
    }


    function upload_group_qr_to_msg_tmpl($user)
    {
        $group_qr_list = $this->search_group_qr_one($user['dep_name']);
        dump($group_qr_list);
        foreach ($group_qr_list as $key => $value) {
            $image_ids = $this->upload_img($value['qrCode']);
            dump(['上传' => $image_ids]);
            $coverUrl = $image_ids['data']['groupId'];
            $response = $this->add_message_img_tmpl([
                'title' => $value['name'],
                'coverUrl' => $coverUrl,
                'columnIds' => $this->massage_tmpl_group_ids[$user['dep']]

            ]);
            dump(['添加群活码图片附件' => $response]);
            if ($response['success']) {
                Db::table('dp_suosi_user1')->where(['dep_name' => $value['name']])->update(['msg_tmpl_qr_status' => 1]);
            }
        }
    }


    function update()
    {
        $datas = $this->get_group_list();
        foreach ($datas as $key => $data) {
            sleep(rand(1, 5));
            $tags = [];
            if (isset($this->grpup_ids[$data['groupId']])) {
                $type_name = $this->grpup_ids[$data['groupId']];

                dump($data['name']);
                $db = Db::table('dp_suosi_user1')->where(['dep' => $type_name, 'dep_name' => $data['name']])->find();

                // $grpup_content_ids = $this->grpup_content_ids[$db['dep_type'] . '中心'];
                dump(Db::getLastSql());
                dump($db);
                if ($db) {
                    $tags[] = $this->search_group_tag($db['dep_type']);
                }

                $tags[] = $this->search_group_tag($type_name);

                $tags = array_filter($tags, function ($item) {
                    return count($item) > 0;
                });

                $groups = $this->search_group_name($data['roomBaseName']);
                if ($groups) {
                    $params = [
                        "id" => $groups['id'],
                        'groupLabelSignature' => $tags
                    ];
                    dump(['go' => $params]);
                    $this->update_group_tag($params);
                }
                unset($tags);

            }

        }
    }
}


